<template>
  <el-dialog
    top="30px"
    width="800px"
    :before-close="beforeClose"
    append-to-body
    :close-on-click-modal="false"
    :title="innerTitle"
    :visible.sync="visible"
  >
    <el-form
      :model="editCustomerData"
      v-loading="loading"
      label-position="left"
      size="small"
      :rules="rules"
      ref="form"
      label-width="130px"
    >
      <el-form-item label="企业名称" prop="customer_name">
        <el-autocomplete
          v-model="editCustomerData.customer_name"
          class="form-control-ml"
          placeholder="请输入企业名称"
          popper-class="customer-autocomplete"
          value-key="customer_name"
          :fetch-suggestions="throttleGetData"
          @input="clearId"
          @select="handleSelectFarm"
        >
          <template slot-scope="props">
            <div class="farm-name">{{ props.item.customer_name }}</div>
            <small class="text-muted">{{ props.item.address_detail }}</small>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="经营地址" prop="address_code">
        <select-address
          class="form-control-ml"
          clearable
          v-model="editCustomerData.address_code"
          auto-top
        ></select-address>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input
          v-model="editCustomerData.address_detail"
          class="form-control-ml"
          placeholder="详细地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="组织类型" prop="org_class">
        <select-farm-org
          v-model="editCustomerData.org_class"
          class="form-control-ml"
        ></select-farm-org>
      </el-form-item>

      <el-form-item label="统一社会信用代码">
        <el-input
          v-model="editCustomerData.register_no"
          class="form-control-ml"
          placeholder="统一社会信用代码"
        >
          <el-button slot="append" class="input-group-text" type="info" @click="linkto">
            工商信息
          </el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="负责人" prop="corp_name">
        <el-input
          v-model="editCustomerData.corp_name"
          class="form-control-ml"
          placeholder="请输入负责人名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="负责人身份证" prop="lender_idcard">
        <el-input
          v-model="editCustomerData.lender_idcard"
          class="form-control-ml"
          placeholder="请输入负责人身份证"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile_no">
        <el-input
          v-model="editCustomerData.mobile_no"
          class="form-control-ml"
          placeholder="请输入负责人联系电话"
        ></el-input>
      </el-form-item>

      <el-form-item label="主营产业" prop="main_business">
        <c-select
          :options="enumIndustryType"
          class="form-control-ml"
          v-model="editCustomerData.main_business"
          placeholder="请选择主营产业"
        ></c-select>
      </el-form-item>

      <el-form-item label="经营范围" prop="business_scope">
        <el-input
          v-model="editCustomerData.business_scope"
          class="form-control-ml"
          placeholder="请输入经营范围"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否扶贫项目">
        <el-radio v-model="editCustomerData.is_poverty_project" label="1">是</el-radio>
        <el-radio v-model="editCustomerData.is_poverty_project" label="0">否</el-radio>
      </el-form-item>
      <el-form-item label="带动农户" prop="poverty_households">
        <el-input
          v-model="editCustomerData.poverty_households"
          type="number"
          class="form-control-ml"
          placeholder="请输入带动农户数量"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>

      <el-form-item label="申请金额" prop="apply_funds">
        <el-input
          v-model="editCustomerData.apply_funds"
          type="number"
          class="form-control-ml"
          placeholder="请输入申请金额"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>

      <el-form-item label="贷款年限" prop="load_years">
        <el-input
          v-model="editCustomerData.load_years"
          type="number"
          class="form-control-ml"
          placeholder="请输入贷款年限"
        >
          <span slot="append">年</span>
        </el-input>
      </el-form-item>

      <el-form-item label="资金用途" prop="funds_use_dir">
        <el-input
          v-model="editCustomerData.funds_use_dir"
          class="form-control-ml"
          placeholder="请输入资金用途"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="是否指定担保机构">
        <el-switch v-model="isCredit"
                   active-color="#67C23A"
                   inactive-color="#409EFF"
                   active-value="1"
                   active-text="是"
                   inactive-value="0"
                   inactive-text="否">
        </el-switch>
      </el-form-item> -->
      <!-- <el-form-item label="担保机构"
                    prop="service_id"
                    v-if="+isCredit === 1">
        <c-select :options="agencies"
                  :props="{value: 'client_id', label: 'org_name'}"
                  v-model="editCustomerData.service_id"
                  class="form-control-ml"></c-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { idCardValidator, phoneValidator } from '@/common/plugins/validator'
import SelectAddress from '@/components/select/SelectAddress'
import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import { addressFromLevel, throttle } from '@vimi/utils-tool'
// import { createFarm, putFarm } from '@/common/api/industrial'
import { enumIndustryType, enumParentMainBusiness } from '@/bank/plugins/enum'
export default {
  components: {
    SelectFarmOrg,
    SelectAddress,
  },
  props: {
    visible: Boolean,
    customerRelatedId: String,
    ProjectType: {
      type: String,
      default: '1',
    },
    title: String,
    // 受理
    approveType: Boolean,
  },
  data() {
    return {
      enumIndustryType,
      enumParentMainBusiness,
      customerParams: {
        index: 1,
        size: 30,
        customer_name: '',
      },
      tableName: 'customer_related',
      publicId: null,
      editCustomerData: {
        customer_name: '',
        corp_name: '',
        lender_idcard: '',
        address_code: '',
        address_detail: '',
        org_class: '',
        mobile_no: '',
        apply_funds: '',
        register_no: '',
        poverty_households: '',
        business_scope: '',
        load_years: '',
        // service_id: '',
        funds_use_dir: '',
        main_business: '',
        is_poverty_project: '0',
        submit_type: 5,
      },
      // initCustomerData: {},
      rules: {
        customer_name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { required: true, message: '请输入企业名称', trigger: 'change' },
        ],
        corp_name: { required: true, message: '请输入负责人名字', trigger: 'blur' },
        lender_idcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: idCardValidator, message: '身份证号格式错误', trigger: 'blur' },
        ],
        address_code: { required: true, message: '请选择经营地址', trigger: 'change' },
        org_class: { required: true, message: '请选择组织类型', trigger: 'change' },
        mobile_no: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: phoneValidator, message: '电话号码错误', trigger: 'blur' },
        ],
        apply_funds: { required: true, message: '请输入申请金额', trigger: 'blur' },
        load_years: { required: true, message: '请输入贷款年限', trigger: 'blur' },
        funds_use_dir: { required: true, message: '请输入资金用途', trigger: 'blur' },
        // service_id: { required: true, message: '请选择担保机构', trigger: 'change' },
        main_business: { required: true, message: '请选择主营产业', trigger: 'change' },
      },
      saveLoading: false,
      loading: false,
      // isCredit: '0',
      tableData: {},
      agencyLoading: false,
      agencies: [],
    }
  },
  computed: {
    user() {
      return this.$store.getters.user
    },
    type() {
      return !this.customerRelatedId
    },
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode
    },
    orgRegionLever() {
      return this.user.orgRegionLever
    },
    innerTitle() {
      return this.title || `${this.type ? '新增' : '修改'}项目库`
    },
  },
  watch: {
    customerRelatedId() {
      if (this.customerRelatedId) {
        this.getData()
      } else {
        this.tableData = {}
        this.setCustomerData(this.tableData)
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    },
    // tableData: {
    //   handler: function () {
    //     if (this.tableData.service_id || this.tableData.recommend_service) {
    //       this.isCredit = '1'
    //     } else {
    //       this.isCredit = '0'
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },
  },
  mounted() {},
  created() {
    this.customerParams.address_code = this.$utils.getAddressCode()
    // this.initCustomerData = { ...this.editCustomerData }
    this.getAgencyByParams()
  },
  methods: {
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getCustomer(queryString, cb)
    }),

    async getAgencyByParams() {
      if (!this.queryAddressCode) {
        return
      }
      let params = {}
      if (this.orgRegionLever > 2) {
        params = {
          'orWhere.address_code.eq': [
            addressFromLevel(this.queryAddressCode, 2),
            addressFromLevel(this.queryAddressCode, 3),
          ],
        }
      } else {
        params = {
          'address_code.endlike': this.queryAddressCode.replace(/0*$/g, ''),
        }
      }
      this.agencyLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'credit_select_view', params, {
          N1address_code: 'asc',
        })
      )
      this.agencyLoading = false
      this.agencies = (res && res.data) || []
    },
    async getData() {
      // 通过传入的customer_related_id获取到客户信息
      const params = { 'customer_related_id.eq': this.customerRelatedId }
      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, params)
      )
      this.loading = false
      if (err) {
        return this.$message.error('获取客户信息失败！')
      }
      const data = (res && res.data && res.data.length && res.data[0]) || {}

      this.tableData = data
      this.setCustomerData(data)
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.onSubmit()
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    onSubmit() {
      // if (+this.isCredit !== 1) {
      //   this.editCustomerData.service_id = null
      // }
      const data = {
        submit_type: this.editCustomerData.submit_type || 5,
        customer_name: this.editCustomerData.customer_name,
        corp_name: this.editCustomerData.corp_name,
        mobile_no: this.editCustomerData.mobile_no,
        address_code: this.editCustomerData.address_code,
        address_detail: this.editCustomerData.address_detail,
        register_no: this.editCustomerData.register_no,
        org_class: this.editCustomerData.org_class,
        lender_idcard: this.editCustomerData.lender_idcard,
        project_type: this.ProjectType,
        main_business: this.editCustomerData.main_business,
        parent_main_business: enumParentMainBusiness[this.editCustomerData.main_business] || '',
        poverty_households: this.editCustomerData.poverty_households,
        business_scope: this.editCustomerData.business_scope,
        is_poverty_project: this.editCustomerData.is_poverty_project,
        // service_id: this.editCustomerData.service_id || null,
        apply_funds: this.editCustomerData.apply_funds,
        load_years: this.editCustomerData.load_years,
        funds_use_dir: this.editCustomerData.funds_use_dir,
      }
      if (this.editCustomerData.customer_id) {
        data.customer_id = this.editCustomerData.customer_id
      } else {
        data.submit_client_id = this.$store.getters.clientId
        data.submit_client_name = this.$store.getters.org.orgName
        data.submit_person_name = this.$store.getters.user.userName
        data.bank_id = this.$store.getters.clientId
        data.bank_code = this.$store.getters.org.orgCode
        data.bank_name = this.$store.getters.org.orgName
      }

      // 受理，更改状态
      if (this.approveType) {
        data.channel_claim_status = 1
      }

      if (!this.customerRelatedId) {
        this.addFarm(data)
      } else {
        this.updateFarm(data)
      }
    },
    updateFarm(data) {
      this.saveLoading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.customerRelatedId, data)
        .then(() => {
          this.$message.success('修改客户成功！')
          this.getData()
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(err => {
          if (err) {
            const errStr = typeof err.data === 'string' ? err.data : '修改客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    addFarm(data) {
      this.saveLoading = true
      this.$api
        .addData(this.$serviceName, this.tableName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(err => {
          const errStr = typeof err.data === 'string' ? err.data : '添加客户失败，请重试！'
          return this.$message.error(`${errStr}`)
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    beforeClose() {
      this.setCustomerData(this.tableData)
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      this.$emit('update:visible', false)
    },
    handleSelectFarm(customer) {
      this.setCustomerData(customer)
    },
    setCustomerData(customer) {
      Object.keys(this.editCustomerData).forEach(key => {
        this.editCustomerData[key] = customer[key] || ''
      })
      this.editCustomerData.customer_id = customer.customer_id
      // this.initCustomerData = { ...this.editCustomerData }
    },
    clearId() {
      if (this.customerRelatedId) {
        return
      }
      this.editCustomerData.customer_id = ''
    },
    async getCustomer(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []

      if (this.customerParams.customer_name === queryString) {
        cb(data)
        return
      }

      this.customerParams.customer_name = queryString
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_info_warehouse', this.customerParams)
      )

      if (res && res.data) {
        data = res.data.data || []
      }

      cb(data)
    },
    linkto() {
      window.open('http://www.gsxt.gov.cn/index.html')
    },
  },
}
</script>
<style lang="scss" scoped></style>
